﻿using System;
using WeDonekRpc.Client;
using WeDonekRpc.Client.Interface;
using WeDonekRpc.Helper;

using WeDonekRpc.WebSocketGateway.Interface;
using WeDonekRpc.WebSocketGateway.Model;

namespace WeDonekRpc.WebSocketGateway
{
    internal class ApiRoute : IApiRoute
    {
        private readonly ISocketApi _Api = null;

        private readonly IApiModular _Modular = null;
        private readonly Action<IApiSocketService> _AccreditVer = null;

        public ApiRoute ( ISocketApi api, ApiModel model, IRouteConfig config, IApiModular modular )
        {
            this._Api = api;
            this._AccreditVer = config.AccreditVer;
            this._Modular = modular;
            this.Prower = model.Power;
            this.IsAccredit = model.IsAccredit;
            this.LocalPath = api.LocalPath;
        }
        public string LocalPath { get; }

        public string ServiceName => this._Modular.ServiceName;
        public bool IsAccredit { get; } = false;

        public string[] Prower { get; } = null;


        public void ExecApi ( Interface.IWebSocketService service )
        {
            using ( IScoreService scope = RpcClient.Ioc.CreateScore() )
            {
                service.InitService(this._Modular);
                this._CheckAccredit(service);
                this._Api.ExecApi(service);
            }
        }

        private void _CheckAccredit ( Interface.IWebSocketService service )
        {
            this._AccreditVer?.Invoke(service);
            if ( !this.IsAccredit )
            {
                return;
            }
            else if ( service.UserState == null )
            {
                throw new ErrorException("accredit.unauthorized");
            }
            else if ( this.Prower != null && !service.UserState.CheckPower(this.Prower) )
            {
                throw new ErrorException("accredit.no.power");
            }

        }


        public void RegApi ()
        {
            this._Api.RegApi(this);
        }
    }
}
